package com.jsu.clubmanagementsystem.controller.activity;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jsu.clubmanagementsystem.common.BaseResponse;
import com.jsu.clubmanagementsystem.common.DeleteRequest;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.activity.ActivityAddRequest;
import com.jsu.clubmanagementsystem.model.dto.activity.ActivityQueryRequest;
import com.jsu.clubmanagementsystem.model.dto.activity.ActivityUpdateRequest;
import com.jsu.clubmanagementsystem.model.dto.activitymembership.ActivityMembershipUpdateRequest;
import com.jsu.clubmanagementsystem.model.entity.*;
import com.jsu.clubmanagementsystem.model.enums.ApplicationTypeEnum;
import com.jsu.clubmanagementsystem.model.enums.ReviewResultEnum;
import com.jsu.clubmanagementsystem.service.activity.ActivityService;
import com.jsu.clubmanagementsystem.service.application.ActivityApplicationService;
import com.jsu.clubmanagementsystem.service.application.UserApplicationService;
import com.jsu.clubmanagementsystem.service.club.ClubService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/activity")
public class AdminActivityController {

    @Resource
    private ClubService clubService;

    @Resource
    private ActivityService activityService;

    @Resource
    private UserService userService;

    @Resource
    private UserApplicationService userApplicationService;

    @Resource
    private ActivityApplicationService activityApplicationService;

    /**
     * 增加社团活动
     * @param activityAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addActivity(@RequestBody ActivityAddRequest activityAddRequest, HttpServletRequest request) {
        if(activityAddRequest == null){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        Activity activity = new Activity();
        BeanUtils.copyProperties(activityAddRequest, activity);
        return ResultUtils.success(activityService.addActivity(activity));
    }

    /**
     * 删除社团活动
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteActivity(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }
        Long activityId = deleteRequest.getId();
        Activity activity = activityService.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标活动不存在");
        }

        QueryWrapper<UserApplication> userApplicationQueryWrapper = new QueryWrapper<>();
        userApplicationQueryWrapper.in("type",
                ApplicationTypeEnum.ENGAGE_ACTIVITY.getCode(), ApplicationTypeEnum.QUIT_ACTIVITY.getCode());
        userApplicationQueryWrapper.eq("additionalInfo", activityId);
        userApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (userApplicationService.count(userApplicationQueryWrapper) > 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "活动还有未审核的申请");
        }

        QueryWrapper<ActivityApplication> activityApplicationQueryWrapper = new QueryWrapper<>();
        activityApplicationQueryWrapper.eq("type", ApplicationTypeEnum.CHANGE_ACTIVITY_INFO.getCode());
        activityApplicationQueryWrapper.eq("targetId", activityId);
        if (activityApplicationService.count(activityApplicationQueryWrapper) > 0 &&
                !activityApplicationService.remove(activityApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除活动未被审核的修改信息申请失败");
        }

        return ResultUtils.success(activityService.deleteActivity(activity));
    }

    /**
     * 修改社团活动信息 (仅管理员)
     * @param updateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateActivity(@RequestBody ActivityUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        Activity activity = new Activity();
        BeanUtils.copyProperties(updateRequest, activity);
        return ResultUtils.success(activityService.updateActivity(activity));
    }

    /**
     * 添加成员 (管理员、社长)
     *
     * @param addRequest 添加请求
     * @param request    HTTP请求
     * @return 添加结果
     */
    @PostMapping("/member/add")
    public BaseResponse<Boolean> addMemberToActivity(@RequestBody ActivityMembershipUpdateRequest addRequest, HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long activityId = addRequest.getActivityId();
        if (activityId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Activity activity = activityService.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标活动不存在");
        }
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN) &&
                !clubService.isManagerOfClub(loginUser.getId(), activity.getClubId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        QueryWrapper<UserApplication> userApplicationQueryWrapper = new QueryWrapper<>();
        userApplicationQueryWrapper.eq("type", ApplicationTypeEnum.ENGAGE_ACTIVITY.getCode());
        userApplicationQueryWrapper.eq("userId", addRequest.getUserId());
        userApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (userApplicationService.count(userApplicationQueryWrapper) > 0 &&
                !userApplicationService.remove(userApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "处理该用户未被审核的参加活动申请失败");
        }

        ActivityMembership membership = new ActivityMembership();
        BeanUtils.copyProperties(addRequest, membership);
        return ResultUtils.success(activityService.addMemberToActivity(membership));
    }

    /**
     * 移除成员 (管理员、社长)
     *
     * @param deleteRequest 删除请求
     * @param request       HTTP请求
     * @return 删除结果
     */
    @PostMapping("/member/delete")
    public BaseResponse<Boolean> deleteMemberFromActivity(@RequestBody ActivityMembershipUpdateRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数不能为空");
        }
        Long activityId = deleteRequest.getActivityId();
        if (activityId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Activity activity = activityService.getById(activityId);
        if (activity == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标活动不存在");
        }
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserRole().equals(UserConstant.USER_ROLE_ADMIN) &&
                !clubService.isManagerOfClub(loginUser.getId(), activity.getClubId())) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        QueryWrapper<UserApplication> userApplicationQueryWrapper = new QueryWrapper<>();
        userApplicationQueryWrapper.eq("type", ApplicationTypeEnum.QUIT_ACTIVITY.getCode());
        userApplicationQueryWrapper.eq("userId", deleteRequest.getUserId());
        userApplicationQueryWrapper.eq("result", ReviewResultEnum.WAITING.getCode());
        if (userApplicationService.count(userApplicationQueryWrapper) > 0 &&
                !userApplicationService.remove(userApplicationQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "处理该用户未被审核的退出活动申请失败");
        }

        ActivityMembership membership = new ActivityMembership();
        BeanUtils.copyProperties(deleteRequest, membership);
        return ResultUtils.success(activityService.deleteMemberFromActivity(membership));
    }

    /**
     * 查看社团活动 (仅管理员)
     * @param activityId
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Activity> getActivityById(long activityId, HttpServletRequest request){
        if ( !activityService.isExist(activityId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "活动不存在");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        Activity activity = activityService.getById(activityId);
        return ResultUtils.success(activity);
    }

    /**
     * 查找社团活动 (仅管理员)
     * @param queryRequest
     * @param request
     * @return
     */
    @PostMapping("/list")
    public BaseResponse<Page<Activity>> listActivityByPage(@RequestBody ActivityQueryRequest queryRequest, HttpServletRequest request) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "无权限执行此操作");
        }

        QueryWrapper<Activity> queryWrapper = activityService.getQueryWrapper(queryRequest);
        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        Page<Activity> page = activityService.page(new Page<>(current, pageSize), queryWrapper);
        return ResultUtils.success(page);
    }
}
